const { sequelize } = require("../../core/db");
const { Sequelize, Model } = require("sequelize");

class Raffle extends Model {
  static async verify(raffle_id, probability) {
    if (raffle_id) {
      const count = await Raffle.sum("probability", {
        where: {
          raffle_id: {
            [Sequelize.Op.ne]: raffle_id,
          },
        },
      });

      if (count.probability + probability >= 100) {
        throw new global.errs.AuthFailed("概率不能超过100%");
      }
    } else {
      const count = await Raffle.sum("probability");

      if (count.probability + probability >= 100) {
        throw new global.errs.AuthFailed("概率不能超过100%");
      }
    }
  }
}
class Raffle_record extends Model {}

// 中奖记录表
Raffle_record.init(
  {
    raffle_record_id: {
      type: Sequelize.INTEGER,
      primaryKey: true,
      autoIncrement: true,
    },
    uid: {
      type: Sequelize.STRING,
      allowNull: false,
    },
    point: {
      type: Sequelize.INTEGER,
      defaultValue: 0,
      comment: "用户消耗积分",
    },
    tracking_number: {
      type: Sequelize.STRING,
      comment: "快递单号",
    },
    address: {
      type: Sequelize.INTEGER,
      comment: "快递地址",
    },
    raffle_id: {
      type: Sequelize.INTEGER,
      comment: "奖品id",
    },
    raffle_details: {
      type: Sequelize.TEXT,
      comment: "奖品详情",
    },
  },
  {
    sequelize,
    tableName: "raffle_record",
  }
);

// 奖品表
Raffle.init(
  {
    raffle_id: {
      type: Sequelize.INTEGER,
      primaryKey: true,
      autoIncrement: true,
    },
    del: {
      type: Sequelize.BOOLEAN,
      defaultValue: false,
      comment: "是否上架",
    },
    probability: {
      type: Sequelize.STRING,
      allowNull: false,
      comment: "中奖概率",
    },
    prize_name: {
      type: Sequelize.STRING,
      comment: "奖品名",
    },
    prize_image: {
      type: Sequelize.STRING,
      comment: "奖品图片",
    },
    introduce: {
      type: Sequelize.TEXT,
      comment: "奖品介绍",
    },
    point: {
      type: Sequelize.INTEGER,
      defaultValue: 10,
      comment: "奖品消耗积分",
    },
    stock: {
      type: Sequelize.INTEGER,
      comment: "奖品库存",
    },
  },
  {
    sequelize,
    tableName: "raffle",
  }
);

module.exports = {
  Raffle_record,
  Raffle,
};
